<?php


namespace app\agent\service;

class AgentService
{
	public static function get_agent_authority_config($app, $agent, $isAgentBindingConfig = false)
	{
		$item = \think\Db::name("app_agent_binding")->where(["appid" => $app["id"], "agent_id" => $agent["id"]])->find();
		$item["authority_config"] = json_decode($item["authority_config"], true);
		$agent_config = json_decode($app["agent_config"], true);
		if (empty($item)) {
			return null;
		}
		$authority_config = ["price" => [0 => !empty($item["authority_config"]["price"][0]) ? $item["authority_config"]["price"][0] : ($agent["level"] === 1 ? $agent_config["price"][0] ?? "" : ""), 1 => !empty($item["authority_config"]["price"][1]) ? $item["authority_config"]["price"][1] : ($agent["level"] === 1 ? $agent_config["price"][1] ?? "" : ""), 2 => !empty($item["authority_config"]["price"][2]) ? $item["authority_config"]["price"][2] : ($agent["level"] === 1 ? $agent_config["price"][2] ?? "" : ""), 3 => !empty($item["authority_config"]["price"][3]) ? $item["authority_config"]["price"][3] : ($agent["level"] === 1 ? $agent_config["price"][3] ?? "" : ""), 4 => !empty($item["authority_config"]["price"][4]) ? $item["authority_config"]["price"][4] : ($agent["level"] === 1 ? $agent_config["price"][4] ?? "" : ""), 7 => !empty($item["authority_config"]["price"][7]) ? $item["authority_config"]["price"][7] : ($agent["level"] === 1 ? $agent_config["price"][7] ?? "" : ""), 8 => !empty($item["authority_config"]["price"][8]) ? $item["authority_config"]["price"][8] : ($agent["level"] === 1 ? $agent_config["price"][8] ?? "" : ""), 5 => !empty($item["authority_config"]["price"][5]) ? $item["authority_config"]["price"][5] : ($agent["level"] === 1 ? $agent_config["price"][5] ?? "" : ""), 6 => !empty($item["authority_config"]["price"][6]) ? $item["authority_config"]["price"][6] : ($agent["level"] === 1 ? $agent_config["price"][6] ?? "" : "")]];
		if ($isAgentBindingConfig) {
			$authority_config = ["price" => [0 => $item["authority_config"]["price"][0] ?? "", 1 => $item["authority_config"]["price"][1] ?? "", 2 => $item["authority_config"]["price"][2] ?? "", 3 => $item["authority_config"]["price"][3] ?? "", 4 => $item["authority_config"]["price"][4] ?? "", 7 => $item["authority_config"]["price"][7] ?? "", 8 => $item["authority_config"]["price"][8] ?? "", 5 => $item["authority_config"]["price"][5] ?? "", 6 => $item["authority_config"]["price"][6] ?? ""]];
		}
		$authority_config["add_card_minimum_face_value_config"] = $item["authority_config"]["add_card_minimum_face_value_config"] ?? [];
		$authority_config["add_card_maximum_face_value_config"] = $item["authority_config"]["add_card_maximum_face_value_config"] ?? [];
		$authority_config["add_card_minimum_quantity_config"] = $item["authority_config"]["add_card_minimum_quantity_config"] ?? [];
		$authority_config["add_card_maximum_quantity_config"] = $item["authority_config"]["add_card_maximum_quantity_config"] ?? [];
		$authority_config["hide_show_config"] = $item["authority_config"]["hide_show_config"] ?? [];
		$authority_config["add_card_structure_head_config"] = $item["authority_config"]["add_card_structure_head_config"] ?? [];
		$authority_config["add_card_structure_body_config"] = $item["authority_config"]["add_card_structure_body_config"] ?? [];
		$authority_config["add_card_structure_body_length_config"] = $item["authority_config"]["add_card_structure_body_length_config"] ?? [];
		$authority_config["add_card_structure_body_transform_config"] = $item["authority_config"]["add_card_structure_body_transform_config"] ?? [];
		$authority_config["add_card_structure_foot_config"] = $item["authority_config"]["add_card_structure_foot_config"] ?? [];
		$authority_config["agent_price_difference_bonus_proportion_type"] = $item["authority_config"]["agent_price_difference_bonus_proportion_type"] ?? -1;
		$authority_config["agent_price_difference_bonus_proportion"] = $item["authority_config"]["agent_price_difference_bonus_proportion"] ?? "";
		$authority_config["agent_price_difference_bonus_hierarchy_limit_type"] = $item["authority_config"]["agent_price_difference_bonus_hierarchy_limit_type"] ?? -1;
		$authority_config["agent_price_difference_bonus_hierarchy_limit"] = $item["authority_config"]["agent_price_difference_bonus_hierarchy_limit"] ?? 0;
		if ($isAgentBindingConfig) {
			$authority_config["add_card_minimum_face_value_config"] = (object) $authority_config["add_card_minimum_face_value_config"];
			$authority_config["add_card_maximum_face_value_config"] = (object) $authority_config["add_card_maximum_face_value_config"];
			$authority_config["add_card_minimum_quantity_config"] = (object) $authority_config["add_card_minimum_quantity_config"];
			$authority_config["add_card_maximum_quantity_config"] = (object) $authority_config["add_card_maximum_quantity_config"];
			$authority_config["hide_show_config"] = (object) $authority_config["hide_show_config"];
			$authority_config["add_card_structure_head_config"] = (object) $authority_config["add_card_structure_head_config"];
			$authority_config["add_card_structure_body_config"] = (object) $authority_config["add_card_structure_body_config"];
			$authority_config["add_card_structure_body_length_config"] = (object) $authority_config["add_card_structure_body_length_config"];
			$authority_config["add_card_structure_foot_config"] = (object) $authority_config["add_card_structure_foot_config"];
		}
		$authority_config["price"]["point"] = !empty($item["authority_config"]["price"]["point"]) ? $item["authority_config"]["price"]["point"] : ($agent["level"] === 1 ? $agent_config["price"]["point"] ?? "" : "");
		if ($isAgentBindingConfig) {
			$authority_config["price"]["point"] = $item["authority_config"]["price"]["point"] ?? "";
		}
		if ($app["type"] == 1) {
			$authority_config["price"]["register_code"] = !empty($item["authority_config"]["price"]["register_code"]) ? $item["authority_config"]["price"]["register_code"] : ($agent["level"] === 1 ? $agent_config["price"]["register_code"] ?? "" : "");
			if ($isAgentBindingConfig) {
				$authority_config["price"]["register_code"] = $item["authority_config"]["price"]["register_code"] ?? "";
			}
		}
		if ($app["type"] == 0) {
			$authority_config["card_unbinding"] = self::get_authority_config_item($item, $agent_config, "card_unbinding");
			$authority_config["card_disable_enable"] = self::get_authority_config_item($item, $agent_config, "card_disable_enable");
			$authority_config["card_delete"] = self::get_authority_config_item($item, $agent_config, "card_delete");
			$authority_config["card_batch_delete"] = self::get_authority_config_item($item, $agent_config, "card_batch_delete");
			if ($isAgentBindingConfig) {
				$authority_config["card_unbinding"] = $item["authority_config"]["card_unbinding"] ?? -1;
				$authority_config["card_disable_enable"] = $item["authority_config"]["card_disable_enable"] ?? -1;
				$authority_config["card_delete"] = $item["authority_config"]["card_delete"] ?? -1;
				$authority_config["card_batch_delete"] = $item["authority_config"]["card_batch_delete"] ?? -1;
			}
		}
		return $authority_config;
	}
	private static function get_authority_config_item($item, $agent_config, $key)
	{
		$config = $agent_config[$key] ?? false;
		if (isset($item["authority_config"][$key])) {
			if ($item["authority_config"][$key] == 1) {
				return true;
			} elseif ($item["authority_config"][$key] == -1) {
				return $config;
			} else {
				return false;
			}
		} else {
			return $config;
		}
	}
	public static function get_subordinate_list($options)
	{
		$where[] = ["superior_id", "=", $options["uid"]];
		if (isset($options["keyword"]) && $options["keyword"] != "") {
			$where[] = ["", "exp", \think\Db::raw("qq like '%{$options["keyword"]}%' or account like '%{$options["keyword"]}%' or name like '%{$options["keyword"]}%' or id={$options["keyword"]}")];
		}
		$list = \think\Db::name("app_agent")->where($where)->order(["id" => "desc"])->page($options["page"], $options["limit"])->select();
		$count = \think\Db::name("app_agent")->where($where)->count();
		$pages = ceil($count / $options["limit"]);
		$data = [];
		foreach ($list as $item) {
			$data[] = self::get_subordinate_info_array($item);
		}
		return ["code" => \app\agent\model\Code::success, "data" => $data, "count" => $count, "pages" => $pages];
	}
	public static function get_app_subordinate_list($options)
	{
		$where[] = ["binding.superior_id", "=", $options["uid"]];
		$where[] = ["binding.appid", "=", $options["appid"]];
		if (isset($options["keyword"]) && $options["keyword"] != "") {
			$where[] = ["", "exp", \think\Db::raw("agent.qq like '%{$options["keyword"]}%' or agent.account like '%{$options["keyword"]}%' or agent.name like '%{$options["keyword"]}%' or agent.id={$options["keyword"]}")];
		}
		$list = \think\Db::name("app_agent_binding")->alias("binding")->join("app_agent agent", "agent.id=binding.agent_id ")->where($where)->order(["binding.id" => "desc"])->group("agent.id")->page($options["page"], $options["limit"])->select();
		$count = \think\Db::name("app_agent_binding")->alias("binding")->join("app_agent agent", "agent.id=binding.agent_id ")->where($where)->group("agent.id")->count();
		$pages = ceil($count / $options["limit"]);
		$data = [];
		foreach ($list as $item) {
			$item["agent_info"] = self::get_subordinate_info_array(\think\Db::name("app_agent")->where(["id" => $item["agent_id"]])->find());
			$item["authority_config"] = json_decode($item["authority_config"], true) ?? [];
			$item["authority_config"]["price"] = $item["authority_config"]["price"] ?? (object) [];
			$data[] = $item;
		}
		return ["code" => \app\agent\model\Code::success, "data" => $data, "count" => $count, "pages" => $pages];
	}
	private static function get_subordinate_info_array($item)
	{
		unset($item["password"]);
		unset($item["token"]);
		$item["app_binding_count"] = \think\Db::name("app_agent_binding")->where(["agent_id" => $item["id"]])->count();
		return $item;
	}
	public static function get_subordinate_info($options)
	{
		$item = \think\Db::name("app_agent")->where(["id" => $options["id"], "superior_id" => $options["uid"]])->find();
		if (empty($item)) {
			return ["code" => \app\agent\model\Code::fail, "msg" => "没有该下级代理"];
		}
		return ["code" => \app\agent\model\Code::success, "data" => self::get_subordinate_info_array($item)];
	}
	public static function set_subordinate_authority($options)
	{
		try {
			\think\Db::startTrans();
			$item = \think\Db::name("app_agent")->where(["id" => $options["agent_id"], "superior_id" => $options["uid"]])->find();
			if (empty($item)) {
				throw new \Exception("没有该下级代理");
			}
			$app = \think\Db::name("app")->where(["id" => $options["appid"]])->find();
			$my = \think\Db::name("app_agent")->where(["id" => $options["uid"]])->find();
			$my_binding = \think\Db::name("app_agent_binding")->where(["agent_id" => $options["uid"], "appid" => $options["appid"]])->find();
			if (!$my_binding) {
				throw new \Exception("您不是该应用下的代理");
			}
			$my_price = self::get_agent_authority_config($app, $my)["price"] ?? [];
			if (!$my_price) {
				throw new \Exception("自身价格配置信息未设置");
			}
			foreach ($my_price as $k => $v) {
				if (!$v || !isset($options["authority_config"]["price"][$k])) {
					$options["authority_config"]["price"][$k] = "";
				} else {
					if ($options["authority_config"]["price"][$k] <= $v && $options["authority_config"]["price"][$k] != "") {
						throw new \Exception(\app\common\model\CardTimeType::getName($k) . "卡价格不能小于{$v}");
					} else {
						if ($options["authority_config"]["price"][$k] <= 0 && $options["authority_config"]["price"][$k] != "") {
							throw new \Exception("价格非法");
						}
					}
				}
			}
			if (!($agent_binding = \think\Db::name("app_agent_binding")->where(["agent_id" => $options["agent_id"], "appid" => $options["appid"]])->find())) {
				$isSystemAuthUnpaid = isSystemAuthUnpaid();
				if ($isSystemAuthUnpaid && \think\Db::name("app_agent_binding")->where(["agent_id" => $options["agent_id"]])->count() >= \app\common\model\FreeQuota::AgentBindingAppQuota) {
					return ["code" => \app\agent\model\Code::fail, "msg" => "当前授权为基础版,一个代理最多只能授权" . \app\common\model\FreeQuota::AgentBindingAppQuota . "个应用" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
				}
				\think\Db::name("app_agent_binding")->insert(["appid" => $options["appid"], "agent_id" => $options["agent_id"], "superior_id" => $options["uid"], "authority_config" => json_encode($options["authority_config"], JSON_UNESCAPED_UNICODE), "time" => time()]);
			} else {
				\think\Db::name("app_agent_binding")->where("id", $agent_binding["id"])->update(["authority_config" => json_encode($options["authority_config"], JSON_UNESCAPED_UNICODE)]);
			}
			\think\Db::commit();
			return ["code" => \app\agent\model\Code::success, "msg" => "设置成功"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\agent\model\Code::fail, "msg" => "操作失败 " . $e->getMessage()];
		}
	}
	public static function subordinate_recharge($options)
	{
		try {
			\think\Db::startTrans();
			$item = \think\Db::name("app_agent")->where(["id" => $options["id"], "superior_id" => $options["uid"]])->find();
			if (empty($item)) {
				throw new \Exception("没有该下级代理");
			}
			$my = \think\Db::name("app_agent")->where(["id" => $options["uid"]])->find();
			if ($my["money"] < $options["number"]) {
				throw new \Exception("当前余额不足");
			}
			\app\common\AppAgent::money($my, $options["number"], 1, "充值给下级代理ID:{$options["id"]},备注:" . $options["remarks"]);
			\app\common\AppAgent::money($item, $options["number"], 0, "来自上级ID:{$options["uid"]}的充值,备注:" . $options["remarks"]);
			\think\Db::commit();
			return ["code" => \app\agent\model\Code::success, "msg" => "充值成功"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\agent\model\Code::fail, "msg" => "操作失败 " . $e->getMessage()];
		}
	}
	public static function add_subordinate($options)
	{
		\think\Db::startTrans();
		try {
			$my = \think\Db::name("app_agent")->where(["id" => $options["uid"]])->find();
			if ($my["add_subordinate_authority"] == 0) {
				throw new \Exception("您没有添加子代理的权限");
			}
			$agent_subordinate_limit_level = \app\common\server\ConfigServer::get("options", "agent_subordinate_limit_level", 0);
			if ($agent_subordinate_limit_level && $agent_subordinate_limit_level <= $my["level"]) {
				throw new \Exception("根据相关层级限制当前已不可添加子代理");
			}
			$account = \think\Db::name("app_agent")->where(["account" => $options["account"]])->find();
			if (!empty($account)) {
				throw new \Exception("该账号不可用");
			}
			$isSystemAuthUnpaid = isSystemAuthUnpaid();
			if ($isSystemAuthUnpaid && \think\Db::name("app_agent")->count() >= \app\common\model\FreeQuota::AgentQuota) {
				return ["code" => \app\agent\model\Code::fail, "msg" => "当前授权为基础版,最多只能拥有" . \app\common\model\FreeQuota::AgentQuota . "个代理账号" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText];
			}
			if ($isSystemAuthUnpaid && $my["level"] + 1 >= \app\common\model\FreeQuota::AgentLevenLimit) {
				throw new \Exception("当前授权为基础版,代理层级最高不能超过" . \app\common\model\FreeQuota::AgentLevenLimit . "级" . \app\common\model\DefaultConfig::SystemAuthUnpaidSuffixText);
			}
			$add_subordinate_authority = 0;
			$divide_subordinate_add_subordinate_authority = 0;
			if ($my["divide_subordinate_add_subordinate_authority"] == 0 && isset($options["add_subordinate_authority"]) && ($options["add_subordinate_authority"] == 1 || $options["divide_subordinate_add_subordinate_authority"] == 1)) {
				return ["code" => \app\agent\model\Code::fail, "msg" => "您没有权限设置该代理的子代权限"];
			} else {
				$add_subordinate_authority = $options["add_subordinate_authority"] ?? $add_subordinate_authority;
				$divide_subordinate_add_subordinate_authority = $options["divide_subordinate_add_subordinate_authority"] ?? $divide_subordinate_add_subordinate_authority;
			}
			$password = GeneratePassword($options["password"]);
			$id = \think\Db::name("app_agent")->insertGetId(["create_time" => time(), "update_time" => time(), "name" => $options["name"], "account" => $options["account"], "password" => $password, "qq" => $options["qq"], "superior_id" => $my["id"], "level" => $my["level"] + 1, "add_subordinate_authority" => $add_subordinate_authority, "divide_subordinate_add_subordinate_authority" => $divide_subordinate_add_subordinate_authority]);
			\think\Db::commit();
			return ["code" => \app\agent\model\Code::success, "msg" => "添加成功"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\agent\model\Code::fail, "msg" => "操作失败 " . $e->getMessage()];
		}
	}
	public static function edit_subordinate($options)
	{
		\think\Db::startTrans();
		try {
			$my = \think\Db::name("app_agent")->where(["id" => $options["uid"]])->find();
			$agent = \think\Db::name("app_agent")->where(["id" => $options["id"], "superior_id" => $options["uid"]])->find();
			if (empty($agent)) {
				return ["code" => \app\agent\model\Code::fail, "msg" => "没有该下级代理"];
			}
			$add_subordinate_authority = $agent["add_subordinate_authority"];
			$divide_subordinate_add_subordinate_authority = $agent["divide_subordinate_add_subordinate_authority"];
			if ($my["divide_subordinate_add_subordinate_authority"] == 0 && isset($options["add_subordinate_authority"]) && ($options["add_subordinate_authority"] == 1 || $options["divide_subordinate_add_subordinate_authority"] == 1)) {
				return ["code" => \app\agent\model\Code::fail, "msg" => "您没有权限设置该代理的子代权限"];
			} else {
				$add_subordinate_authority = $options["add_subordinate_authority"];
				$divide_subordinate_add_subordinate_authority = $options["divide_subordinate_add_subordinate_authority"] ?? 0;
			}
			$data = ["add_subordinate_authority" => $add_subordinate_authority, "divide_subordinate_add_subordinate_authority" => $divide_subordinate_add_subordinate_authority];
			\think\Db::name("app_agent")->where(["id" => $agent["id"]])->update($data);
			\think\Db::commit();
			return ["code" => \app\agent\model\Code::success, "msg" => "编辑成功"];
		} catch (\Exception $e) {
			\think\Db::rollback();
			return ["code" => \app\agent\model\Code::fail, "msg" => "操作失败 " . $e->getMessage()];
		}
	}
	public static function get_subordinate_ids($agent)
	{
		$ids = [];
		if (!$agent) {
			return $ids;
		}
		$subordinate_list = \think\Db::name("app_agent")->where(["superior_id" => $agent["id"]])->select();
		foreach ($subordinate_list as $subordinate) {
			$ids[] = $subordinate["id"];
			$ids = array_merge($ids, self::get_subordinate_ids($subordinate));
		}
		return $ids;
	}
	public static function checkSuperiorPrice($app, $agent, $binding)
	{
		$agent_config = json_decode($app["agent_config"], true);
		if (!isset($agent_config["price"])) {
			throw new \Exception("当前应用未初始化设置应用全局代理配置，请先进行配置相关的参数");
		}
		if ($agent["level"] != 1) {
			if ($agent["superior_id"] != $binding["superior_id"]) {
				\think\Db::name("app_agent_binding")->where(["id" => $binding["id"]])->update(["superior_id" => $agent["superior_id"]]);
				$binding["superior_id"] = $agent["superior_id"];
			}
			$superior_agent = \think\Db::name("app_agent")->where(["id" => $binding["superior_id"]])->find();
			$superior_binding = \think\Db::name("app_agent_binding")->where(["agent_id" => $binding["superior_id"], "appid" => $binding["appid"]])->find();
			if (!empty($superior_binding) && $superior_agent["level"] != 1) {
				$superior_prices = self::get_agent_authority_config($app, $superior_agent)["price"] ?? [];
				$binding_prices = self::get_agent_authority_config($app, $agent)["price"] ?? [];
				foreach ($binding_prices as $k => $v) {
					if (isset($superior_prices[$k]) && $superior_prices[$k] !== "" && $v <= $superior_prices[$k] && $v !== "") {
						return false;
					}
				}
			}
		} else {
			$superior_prices = $agent_config["price"];
		}
		$result = true;
		if ($agent["level"] != 1) {
			$result = self::checkSuperiorPrice($app, $superior_agent, $superior_binding);
		}
		return $result;
	}
	public static function addCardGiveDisparityPriceSuperior($app, $agent, $binding, $type, $value, $num, array $start_sub_agent = [], array $start_agent_authority_config = [], int $bonus_hierarchy_count = 1) : void
	{
		$agent_config = json_decode($app["agent_config"], true);
		$authority_config = self::get_agent_authority_config($app, $agent);
		if (!isset($agent_config["price"])) {
			throw new \Exception("未配置代理价格数据信息");
		}
		if (!empty($binding) && $agent["superior_id"]) {
			$superior_agent = \think\Db::name("app_agent")->where(["id" => $binding["superior_id"]])->find();
			$superior_binding = \think\Db::name("app_agent_binding")->where(["agent_id" => $binding["superior_id"], "appid" => $binding["appid"]])->find();
			if ($superior_agent) {
				$superior_authority_config = self::get_agent_authority_config($app, $superior_agent);
				$superior_prices = $superior_authority_config["price"];
				$binding_prices = $authority_config["price"];
				if (!(isset($superior_prices[$type]) && isset($binding_prices[$type]))) {
					throw new \Exception("存在未配置价格的上级");
				}
				if ($superior_prices[$type] < $binding_prices[$type]) {
					$main_value = $value;
					if ($type == \app\common\model\CardTimeType::Perpetual[0]) {
						$main_value = 1;
					}
					$price = $binding_prices[$type] * $main_value * $num - $superior_prices[$type] * $main_value * $num;
					$original_price = $price;
					$remarks = "应用ID:{$app["id"]},代理ID:{$agent["id"]}制卡差价提成";
					$difference_bonus_proportion = false;
					$agent_price_difference_bonus_proportion = $agent_config["agent_price_difference_bonus_proportion"] ?? 0;
					if (isset($agent_config["agent_price_difference_bonus_proportion_type"]) && $agent_config["agent_price_difference_bonus_proportion_type"] == 1) {
						$difference_bonus_proportion = true;
					}
					if (isset($superior_authority_config["agent_price_difference_bonus_proportion_type"])) {
						if ($superior_authority_config["agent_price_difference_bonus_proportion_type"] == 1) {
							$difference_bonus_proportion = true;
							if (isset($superior_authority_config["agent_price_difference_bonus_proportion"]) && $superior_authority_config["agent_price_difference_bonus_proportion"] !== "") {
								$agent_price_difference_bonus_proportion = $superior_authority_config["agent_price_difference_bonus_proportion"];
							}
						} elseif ($superior_authority_config["agent_price_difference_bonus_proportion_type"] == 0) {
							$difference_bonus_proportion = false;
						}
					}
					if ($difference_bonus_proportion) {
						$price = round($price * ($agent_price_difference_bonus_proportion / 100), 2);
						$remarks = "应用ID:{$app["id"]},代理ID:{$agent["id"]}制卡差价提成({$original_price}的{$agent_price_difference_bonus_proportion}%)";
					}
					if ($price > 0) {
						\app\common\AppAgent::money($superior_agent, $price, 0, $remarks);
					}
				}
				if (!$start_agent_authority_config) {
					$start_agent_authority_config = $authority_config;
				}
				$is_continue_bonus = false;
				$agent_price_difference_bonus_hierarchy_limit = $agent_config["agent_price_difference_bonus_hierarchy_limit"] ?? 0;
				if (isset($start_agent_authority_config["agent_price_difference_bonus_hierarchy_limit_type"]) && $start_agent_authority_config["agent_price_difference_bonus_hierarchy_limit_type"] != -1) {
					$agent_price_difference_bonus_hierarchy_limit = $start_agent_authority_config["agent_price_difference_bonus_hierarchy_limit"] ?? 0;
					if (empty($start_agent_authority_config["agent_price_difference_bonus_hierarchy_limit_type"]) || isset($start_agent_authority_config["agent_price_difference_bonus_hierarchy_limit"]) && $agent_price_difference_bonus_hierarchy_limit && $bonus_hierarchy_count < $agent_price_difference_bonus_hierarchy_limit) {
						$is_continue_bonus = true;
					}
				} else {
					if (empty($agent_config["agent_price_difference_bonus_hierarchy_limit_type"]) || isset($agent_config["agent_price_difference_bonus_hierarchy_limit"]) && $agent_price_difference_bonus_hierarchy_limit && $bonus_hierarchy_count < $agent_price_difference_bonus_hierarchy_limit) {
						$is_continue_bonus = true;
					}
				}
				if ($is_continue_bonus) {
					self::addCardGiveDisparityPriceSuperior($app, $agent, $superior_binding, $type, $value, $num, $start_sub_agent ?: $agent, $start_agent_authority_config ?: $authority_config, $bonus_hierarchy_count + 1);
				}
			}
		}
	}
	public static function addCardLimitHandle($agent_config, $authority_config, $time_value, $card_type, $num)
	{
		$add_card_minimum_face_value_config = $agent_config["add_card_minimum_face_value_config"][$card_type] ?? 0;
		if (isset($authority_config["add_card_minimum_face_value_config"][$card_type]) && $authority_config["add_card_minimum_face_value_config"][$card_type] != "") {
			$add_card_minimum_face_value_config = $authority_config["add_card_minimum_face_value_config"][$card_type] ?? 0;
		}
		if (!empty($add_card_minimum_face_value_config) && $time_value < $add_card_minimum_face_value_config) {
			return ["code" => \app\agent\model\Code::error, "msg" => "生成失败,根据制卡规则面值/时长不能低于" . $add_card_minimum_face_value_config];
		}
		$add_card_maximum_face_value_config = $agent_config["add_card_maximum_face_value_config"][$card_type] ?? 0;
		if (isset($authority_config["add_card_maximum_face_value_config"][$card_type]) && $authority_config["add_card_maximum_face_value_config"][$card_type] != "") {
			$add_card_maximum_face_value_config = $authority_config["add_card_maximum_face_value_config"][$card_type] ?? 0;
		}
		if (!empty($add_card_maximum_face_value_config) && $add_card_maximum_face_value_config < $time_value) {
			return ["code" => \app\agent\model\Code::error, "msg" => "生成失败,根据制卡规则面值/时长不能高于" . $add_card_maximum_face_value_config];
		}
		$add_card_minimum_quantity_config = $agent_config["add_card_minimum_quantity_config"][$card_type] ?? 0;
		if (isset($authority_config["add_card_minimum_quantity_config"][$card_type]) && $authority_config["add_card_minimum_quantity_config"][$card_type] != "") {
			$add_card_minimum_quantity_config = $authority_config["add_card_minimum_quantity_config"][$card_type] ?? 0;
		}
		if (!empty($add_card_minimum_quantity_config) && $num < $add_card_minimum_quantity_config) {
			return ["code" => \app\agent\model\Code::error, "msg" => "生成失败,根据制卡规则生成数量不能低于" . $add_card_minimum_quantity_config];
		}
		$add_card_maximum_quantity_config = $agent_config["add_card_maximum_quantity_config"][$card_type] ?? 0;
		if (isset($authority_config["add_card_maximum_quantity_config"][$card_type]) && $authority_config["add_card_maximum_quantity_config"][$card_type] != "") {
			$add_card_maximum_quantity_config = $authority_config["add_card_maximum_quantity_config"][$card_type] ?? 0;
		}
		if (!empty($add_card_maximum_quantity_config) && $add_card_maximum_quantity_config < $num) {
			return ["code" => \app\agent\model\Code::error, "msg" => "生成失败,根据制卡规则生成数量不能高于" . $add_card_maximum_quantity_config];
		}
		return true;
	}
	public static function get_app_data($options)
	{
		try {
			$appid = $options["appid"];
			$agent_id = $options["id"];
			$app = \think\Db::name("app")->where(["id" => $appid])->find();
			$agent = \think\Db::name("app_agent")->where(["id" => $agent_id])->find();
			if (empty($app)) {
				return ["code" => \app\agent\model\Code::fail, "msg" => "应用id不存在"];
			}
			if (empty($agent)) {
				return ["code" => \app\agent\model\Code::fail, "msg" => "代理id不存在"];
			}
			$cardDataWhere[] = ["appid", "=", $appid];
			$cardDataWhere[] = ["agent_id", "=", $agent_id];
			if (isset($options["card_data_time_type"]) && isset($options["card_data_time_field"]) && isset($options["card_data_time_end"]) && $options["card_data_time_type"] == "custom" && $options["card_data_time_field"] && $options["card_data_time_end"]) {
				if ($options["card_data_time_field"] == "usetime") {
					$cardDataWhere[] = ["status", "=", 1];
				}
				if (!empty($options["card_data_time_start"])) {
					$cardDataWhere[] = [$options["card_data_time_field"], "between", [strtotime($options["card_data_time_start"]), strtotime($options["card_data_time_end"])]];
				} else {
					$cardDataWhere[] = [$options["card_data_time_field"], "<=", strtotime($options["card_data_time_end"])];
				}
			}
			if ($app["type"] === 0) {
				$my_card_data = ["total" => \think\Db::name("app_card_user")->where($cardDataWhere)->count(), "used_total" => \think\Db::name("app_card_user")->where(array_merge($cardDataWhere, [["status", "=", 1]]))->count(), "not_used_total" => \think\Db::name("app_card_user")->where(array_merge($cardDataWhere, [["status", "=", 0]]))->count(), "minute_total" => \think\Db::name("app_card_user")->where(array_merge($cardDataWhere, [["time_type", "=", 0]]))->count(), "hour_total" => \think\Db::name("app_card_user")->where(array_merge($cardDataWhere, [["time_type", "=", 1]]))->count(), "day_total" => \think\Db::name("app_card_user")->where(array_merge($cardDataWhere, [["time_type", "=", 2]]))->count(), "week_total" => \think\Db::name("app_card_user")->where(array_merge($cardDataWhere, [["time_type", "=", 3]]))->count(), "month_total" => \think\Db::name("app_card_user")->where(array_merge($cardDataWhere, [["time_type", "=", 4]]))->count(), "quarter_total" => \think\Db::name("app_card_user")->where(array_merge($cardDataWhere, [["time_type", "=", 7]]))->count(), "half_year_total" => \think\Db::name("app_card_user")->where(array_merge($cardDataWhere, [["time_type", "=", 8]]))->count(), "year_total" => \think\Db::name("app_card_user")->where(array_merge($cardDataWhere, [["time_type", "=", 5]]))->count(), "perpetual_total" => \think\Db::name("app_card_user")->where(array_merge($cardDataWhere, [["time_type", "=", 6]]))->count(), "expired_total" => \think\Db::name("app_card_user")->where(array_merge($cardDataWhere, [["status", "=", 0]], [["endtime", "<", time()]]))->count()];
			}
			if ($app["type"] === 1) {
				$my_card_data = ["total" => \think\Db::name("app_member_card")->where($cardDataWhere)->count(), "used_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["status", "=", 1]]))->count(), "not_used_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["status", "=", 0]]))->count(), "minute_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["time_type", "=", 0]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "hour_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["time_type", "=", 1]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "day_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["time_type", "=", 2]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "week_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["time_type", "=", 3]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "month_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["time_type", "=", 4]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "quarter_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["time_type", "=", 7]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "half_year_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["time_type", "=", 8]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "year_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["time_type", "=", 5]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "perpetual_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["time_type", "=", 6]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "point_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["type", "=", \app\common\model\CardType::Point[0]]]))->count(), "register_code_total" => \think\Db::name("app_member_card")->where(array_merge($cardDataWhere, [["type", "=", \app\common\model\CardType::RegisterCode[0]]]))->count()];
			}
			if ($app["type"] === 2) {
				$my_card_data = ["total" => \think\Db::name("app_auth_card")->where($cardDataWhere)->count(), "used_total" => \think\Db::name("app_auth_card")->where(array_merge($cardDataWhere, [["status", "=", 1]]))->count(), "not_used_total" => \think\Db::name("app_auth_card")->where(array_merge($cardDataWhere, [["status", "=", 0]]))->count(), "minute_total" => \think\Db::name("app_auth_card")->where(array_merge($cardDataWhere, [["time_type", "=", 0]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "hour_total" => \think\Db::name("app_auth_card")->where(array_merge($cardDataWhere, [["time_type", "=", 1]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "day_total" => \think\Db::name("app_auth_card")->where(array_merge($cardDataWhere, [["time_type", "=", 2]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "week_total" => \think\Db::name("app_auth_card")->where(array_merge($cardDataWhere, [["time_type", "=", 3]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "month_total" => \think\Db::name("app_auth_card")->where(array_merge($cardDataWhere, [["time_type", "=", 4]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "quarter_total" => \think\Db::name("app_auth_card")->where(array_merge($cardDataWhere, [["time_type", "=", 7]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "half_year_total" => \think\Db::name("app_auth_card")->where(array_merge($cardDataWhere, [["time_type", "=", 8]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "year_total" => \think\Db::name("app_auth_card")->where(array_merge($cardDataWhere, [["time_type", "=", 5]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "perpetual_total" => \think\Db::name("app_auth_card")->where(array_merge($cardDataWhere, [["time_type", "=", 6]], [["type", "=", \app\common\model\CardType::Time[0]]]))->count(), "point_total" => \think\Db::name("app_auth_card")->where(array_merge($cardDataWhere, [["type", "=", \app\common\model\CardType::Point[0]]]))->count()];
			}
			$my_prices_variation = AgentService::checkSuperiorPrice($app, $agent, \think\Db::name("app_agent_binding")->where(["agent_id" => $agent_id, "appid" => $appid])->find());
			$data = ["info" => ["id" => $app["id"], "name" => $app["name"], "avatar" => $app["avatar"], "type" => $app["type"]], "agent_config" => json_decode($app["agent_config"], true) ?? (object) [], "my_card_data" => $my_card_data, "my_authority_config" => AgentService::get_agent_authority_config($app, $agent), "my_subordinate_count" => \think\Db::name("app_agent_binding")->where(["superior_id" => $agent_id, "appid" => $appid])->count(), "my_prices_variation" => !$my_prices_variation];
			return ["code" => \app\agent\model\Code::success, "msg" => "获取成功", "data" => $data];
		} catch (\Exception $e) {
			return ["code" => \app\agent\model\Code::fail, "msg" => "获取应用数据信息失败：" . $e->getMessage()];
		}
	}
}